package user

import (
	"chaowan/data_source"
	"chaowan/models"
	"chaowan/service"
	"chaowan/utils"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
	"time"
)

func Niudantype(ctx *gin.Context) {

	var goodtype []models.Niudantype
	data_source.Db.Find(&goodtype)

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    goodtype,
		"msg":     "ok",
	})
	return
}

type NiudansRBody struct {
	Data       []models.Niudan `json:"data"`
	PageNo     int             `json:"pageNo"`
	PageSize   int             `json:"pageSize"`
	TotalCount int64           `json:"totalCount"`
	TotalPage  int64           `json:"totalPage"`
}

type NiudansBody struct {
	Page         int    `json:"page"`
	Pagesize     int    `json:"pagesize"`
	Niudantypeid int64  `json:"niudantypeid" gorm:"niudantypeid"`
	Uid          int64  `json:"uid" gorm:"uid"`
	ID           int    `json:"id"`
	Qudao        string `json:"qudao"`
}

func Niudans(ctx *gin.Context) {
	request := NiudansBody{}
	ctx.ShouldBind(&request)
	niudantypeid := request.Niudantypeid
	currentPage := request.Page
	pageSize := request.Pagesize
	uid := request.Uid

	offsetNum := pageSize * (currentPage - 1)
	qudao := request.Qudao
	var qudaos []models.Qudao
	qudaos = service.Qudaolist()
	var qudaoid int64
	for _, q := range qudaos {
		if qudao == q.Value {
			qudaoid = q.ID
		}
	}
	var niudanidarr []int64
	if qudaoid > 0 {
		var zhuanpanqudaos []models.Zhuanpanqudao
		data_source.Db.Where("state = 2").Where("qudaoid = ?", qudaoid).Find(&zhuanpanqudaos)
		for _, z := range zhuanpanqudaos {
			niudanidarr = append(niudanidarr, z.Otherid)
		}
	}

	var count int64
	var users []models.Niudan
	res := data_source.Db.Where("status = 1")
	if len(niudanidarr) > 0 {
		res = res.Where("id not in (?)", niudanidarr)
	}
	if uid > 0 {
		var niudans []models.Niudansql
		niudans = service.Niudanxianshou()
		var niudanidarr1 []int64
		var niudanorder []models.Orderniudanfk
		data_source.Db.Model(&models.Orderniudan{}).Where("uid = ?", uid).Find(&niudanorder)
		inttime, endtime := getCurrentdayStartAndEnd()
		for _, n := range niudans {
			var usernum int64
			var daynum int64
			for _, no := range niudanorder {
				if no.Niudanid == n.ID {
					usernum = usernum + no.Num
					if no.Addtime >= inttime && no.Addtime < endtime {
						daynum = daynum + no.Num
					}
				}
			}
			if usernum >= n.Usernum {
				niudanidarr1 = append(niudanidarr1, n.ID)
			}
			if daynum >= n.Daynum {
				niudanidarr1 = append(niudanidarr1, n.ID)
			}
		}
		res = res.Where("id not in (?)", niudanidarr1)
	}

	if niudantypeid > 0 {
		res = res.Where("niudantypeid = ?", niudantypeid)
	}
	res.Model(&models.Niudan{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("sort asc,id desc").Find(&users)

	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := NiudansRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return
}

func Niudaninfo(ctx *gin.Context) {
	request := GoodsBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	uid := request.Uid

	qudao := request.Qudao
	var qudaos []models.Qudao
	qudaos = service.Qudaolist()
	var qudaoid int64
	for _, q := range qudaos {
		if qudao == q.Value {
			qudaoid = q.ID
		}
	}

	var zhuanpanqudaos models.Zhuanpanqudao
	data_source.Db.Where("state = 2").Where("qudaoid = ?", qudaoid).Where("otherid = ?", id).First(&zhuanpanqudaos)
	if zhuanpanqudaos.ID > 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "该扭蛋机已下架",
		})
		return
	}
	var good models.Niudan
	data_source.Db.Where("id = ?", id).First(&good)
	if good.Status == 2 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "该扭蛋机已下架",
		})
		return
	}
	var collect models.Collect
	data_source.Db.Where("goodid = ?", id).Where("uid = ?", uid).Where("state = 2").First(&collect)
	good.Collect = 1
	if collect.ID > 0 {
		good.Collect = 2
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    good,
		"msg":     "ok",
	})
	return
}

func Niudangoods(ctx *gin.Context) {
	request := FanshanggoodsBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	//currentPage := request.Page
	//pageSize := request.Pagesize
	//offsetNum := pageSize * (currentPage - 1)
	//var count int64
	var niudangoodsql []models.Niudangoodsql
	data_source.Db.Model(&models.Niudangood{}).Select("niudangood.*, goods.name, goods.image, goods.price").Joins("left join goods on goods.id = niudangood.goodid").Where("niudangood.niudanid = ?", id).Find(&niudangoodsql)

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    niudangoodsql,
		"msg":     "ok",
	})
	return
}

func Ndcollect(ctx *gin.Context) {
	request := GoodsBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	uid := request.Uid
	if uid == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    101,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "请登录",
		})
		return
	}

	var collect models.Collect
	data_source.Db.Where("goodid = ?", id).Where("uid = ?", uid).Where("state = 2").First(&collect)
	if collect.ID > 0 {
		data_source.Db.Where("goodid = ?", id).Where("uid = ?", uid).Where("state = 2").Delete(&models.Collect{})
	} else {
		var good models.Niudan
		data_source.Db.Where("id = ?", id).First(&good)
		collectadd := models.Collect{
			Goodid: int64(id),
			Uid:    int64(uid),
			State:  2,
			Name:   good.Name,
			Image:  good.Image,
		}
		data_source.Db.Create(&collectadd)
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}

type NiudanbuyBody struct {
	Niudanid  int64  `json:"niudanid"`
	Uid       int64  `json:"uid"`
	Paystatus int64  `json:"paystatus"`
	Num       int64  `json:"num"`
	Qudao     string `json:"qudao" gorm:"qudao"`
}

func Niudanbuy(ctx *gin.Context) {
	request := NiudanbuyBody{}
	ctx.ShouldBind(&request)
	niudanid := request.Niudanid
	uid := request.Uid
	paystatus := request.Paystatus
	num := request.Num
	qudao := request.Qudao
	ip := ctx.ClientIP()
	if uid == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    101,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "请登录",
		})
		return
	}

	var niudan models.Niudan
	data_source.Db.Where("id = ?", niudanid).First(&niudan)
	if niudan.ID == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    101,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "请选择正确扭蛋机",
		})
		return
	}

	if niudan.Daynum > 0 {
		inttime, endtime := getCurrentdayStartAndEnd()
		var niudanbuyorderdaynum int64
		data_source.Db.Model(&models.Orderniudan{}).Where("niudanid = ?", niudanid).Where("uid = ?", uid).Where("addtime >= ?", inttime).Where("addtime < ?", endtime).Count(&niudanbuyorderdaynum)
		if niudanbuyorderdaynum >= niudan.Daynum {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    101,
				"error":   1,
				"success": 400,
				"data":    "on",
				"msg":     "该赏品每天最多购买" + utils.Int64string(niudan.Daynum) + "次",
			})
			return
		}

	}
	if niudan.Usernum > 0 {
		var niudanbuyordernum int64
		data_source.Db.Model(&models.Orderniudan{}).Where("niudanid = ?", niudanid).Where("uid = ?", uid).Count(&niudanbuyordernum)
		if niudanbuyordernum >= niudan.Usernum {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    101,
				"error":   1,
				"success": 400,
				"data":    "on",
				"msg":     "该赏品最多购买" + utils.Int64string(niudan.Usernum) + "次",
			})
			return
		}
	}

	var niudanprice float64

	if num == 1 {
		niudanprice = niudan.Price
	} else if num == 5 {
		niudanprice = niudan.Fiveprice
	} else if num == 10 {
		niudanprice = niudan.Tenprice
	}

	var user models.User
	data_source.Db.Where("id = ?", uid).First(&user)
	if user.ID == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "用户不存在",
		})
		return
	}
	if paystatus == 3 {
		if user.Daibi < niudanprice {
			ctx.JSON(http.StatusOK, gin.H{
				"code":    400,
				"error":   1,
				"success": 400,
				"data":    "on",
				"msg":     "矿石不足",
			})
			return
		}
	}

	orderno := Generateto(time.Time{})
	orderadd := models.Orderniudan{
		Uid:       uid,
		Niudanid:  niudanid,
		Orderno:   orderno,
		Addtime:   time.Now().Unix(),
		Status:    1,
		Num:       num,
		Price:     niudanprice,
		Paystatus: paystatus,
		Choujiang: 1,
		Qudao:     qudao,
	}
	data_source.Db.Create(&orderadd)
	//startOfToday := time.Now().Truncate(24 * time.Hour)
	startTimestamp := getTodayMidnightTimestamp()
	if paystatus == 1 {
		aliRsp := Goodalipay(orderno, int64(niudanprice*100))

		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    aliRsp,
			"msg":     "ok",
		})
		return
	} else if paystatus == 2 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    orderadd.ID,
			"msg":     "ok",
		})
		return
	} else if paystatus == 3 {
		data_source.Db.Model(&models.Orderniudan{}).Where("id = ?", orderadd.ID).Update("status", 2)
		data_source.Db.Model(&models.User{}).Where("id = ?", uid).Update("daibi", user.Daibi-niudanprice)

		userdaibi := models.Userdaibi{
			Uid:     uid,
			Status:  2,
			Addtime: time.Now().Unix(),
			Daibi:   niudanprice,
			Title:   "扭蛋机",
			State:   7,
			Sydaibi: user.Daibi - niudanprice,
		}
		data_source.Db.Create(&userdaibi)

		userorder := models.Userorder{
			Uid:       uid,
			Addtime:   time.Now().Unix(),
			State:     2,
			Paystatus: paystatus,
			Price:     niudanprice,
			Orderid:   orderadd.ID,
		}
		data_source.Db.Create(&userorder)

		var userdayprice models.Userdayprice
		data_source.Db.Where("uid = ?", uid).Where("addtime = ?", startTimestamp).First(&userdayprice)
		if userdayprice.ID == 0 {
			userdaypriceadd := models.Userdayprice{
				Uid:     uid,
				Addtime: startTimestamp,
				Price:   niudanprice,
			}
			data_source.Db.Create(&userdaypriceadd)
		} else {
			data_source.Db.Model(&models.Userdayprice{}).Where("id = ?", userdayprice.ID).Update("price", userdayprice.Price+niudanprice)
		}
		Zhongjiangnd(orderadd)

		//判断是否升级vip
		service.Vipsj(user, niudanprice)
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    orderadd.ID,
			"msg":     "ok",
		})
		return
	} else if paystatus == 4 {
		data := Wechatpayxcxndj(orderno, niudanprice, user, ip, orderadd.ID)
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    data,
			"msg":     "ok",
		})
		return
	}

}

func Zhongjiangnd(order models.Orderniudan) {
	var integral int64
	var niudan models.Niudan
	data_source.Db.Where("id = ?", order.Niudanid).First(&niudan)
	var zhuanpan models.Zhuanpan
	data_source.Db.Where("fanshangid = ?", order.Niudanid).Where("state = 2").First(&zhuanpan)
	var fanshanggoods []models.Fanshanggood
	var shangjuan models.Shangjuan
	if zhuanpan.ID > 0 {
		dengji := strings.Split(zhuanpan.Dengji, ",")
		if dengji[0] == "" {
			data_source.Db.Where("fanshangid = ?", order.Niudanid).Find(&fanshanggoods)
		} else {
			data_source.Db.Where("fanshangid = ?", order.Niudanid).Where("classify not in (?)", dengji).Find(&fanshanggoods)
		}
		if zhuanpan.Classify == 2 {
			data_source.Db.Where("id = ?", zhuanpan.Shangjuanid).First(&shangjuan)
		}
	} else {
		data_source.Db.Where("fanshangid = ?", order.Niudanid).Find(&fanshanggoods)
	}

	var niudangoods []models.Niudangood
	data_source.Db.Where("niudanid = ?", order.Niudanid).Find(&niudangoods)
	var goodidarr []int64
	var anum int64
	var bnum int64
	var cnum int64
	var dnum int64
	for _, f := range niudangoods {
		if f.Classify == 1 {
			anum = anum + f.Num
		}
		if f.Classify == 2 {
			bnum = bnum + f.Num
		}
		if f.Classify == 3 {
			cnum = cnum + f.Num
		}
		if f.Classify == 4 {
			dnum = dnum + f.Num
		}
	}
	var abili float64
	var bbili float64
	var cbili float64
	var dbili float64

	for k, v := range niudangoods {

		if v.Classify == 1 {
			abili = float64(v.Num) / float64(anum)
			niudangoods[k].Bili = niudan.Chuanshuo * 100 * abili
		} else if v.Classify == 2 {
			bbili = float64(v.Num) / float64(bnum)
			niudangoods[k].Bili = niudan.Shishi * 100 * bbili
		} else if v.Classify == 3 {
			cbili = float64(v.Num) / float64(cnum)
			niudangoods[k].Bili = niudan.Putong * 100 * cbili
		} else if v.Classify == 4 {
			dbili = float64(v.Num) / float64(dnum)
			niudangoods[k].Bili = niudan.Gaoji * 100 * dbili
		}
		goodidarr = append(goodidarr, v.Goodid)
	}
	var goods []models.Goods
	data_source.Db.Where("id in (?)", goodidarr).Where("status = 1").Find(&goods)

	now := time.Now()
	zeroToday := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).Unix()
	var user models.User
	data_source.Db.Where("id = ?", order.Uid).First(&user)
	var orderniudangoods []models.Orderniudangood
	var usershangjuans []models.Usershangjuan
	for i := 0; i < int(order.Num); i++ {
		goodid, dengji := service.GetResult(niudangoods)
		for _, good := range goods {
			if goodid == good.ID {
				orderniudangood := models.Orderniudangood{
					Uid:           order.Uid,
					Goodid:        goodid,
					Goodname:      good.Name,
					Goodimage:     good.Image,
					Goodmojing:    good.Mojing,
					Goodprice:     good.Price,
					Orderniudanid: int64(order.ID),
					Addtime:       zeroToday,
					Num:           1,
					Dengji:        dengji,
					State:         1,
				}
				orderniudangoods = append(orderniudangoods, orderniudangood)
				service.Gooduser(user, good, 1, 2, 1, 0, order.ID)
			}
		}

		addtime := time.Now().Unix()
		if zhuanpan.ID > 0 {
			zhongjian := service.CalculateProbability(int64(zhuanpan.Bili * 100))
			if zhongjian == true {
				if zhuanpan.Classify == 1 {
					integral = integral + zhuanpan.Integral*zhuanpan.Num
				} else if zhuanpan.Classify == 2 {
					if shangjuan.ID > 0 {
						var endtime int64
						if shangjuan.Day > 0 {
							endtime = addtime + shangjuan.Day*864000
						}

						for iu := 0; iu < int(zhuanpan.Num); iu++ {

							usershangjuan := models.Usershangjuan{
								Uid:             order.Uid,
								Addtime:         addtime,
								Day:             shangjuan.Day,
								Name:            shangjuan.Name,
								Image:           shangjuan.Image,
								Daibi:           shangjuan.Daibi,
								Num:             shangjuan.Num,
								Userdaibi:       shangjuan.Userdaibi,
								Status:          1,
								Orderfanshangid: int64(order.ID),
								Endtime:         endtime,
								Shangjuanid:     shangjuan.ID,
								State:           2,
							}
							usershangjuans = append(usershangjuans, usershangjuan)
						}
					}

				}
			}
		}

	}

	data_source.Db.Create(&orderniudangoods)
	data_source.Db.Model(&models.Orderniudan{}).Where("id = ?", order.ID).Update("choujiang", 2)

	if len(usershangjuans) > 0 {
		data_source.Db.Create(&usershangjuans)
	}
	if integral > 0 {
		orderfanshangintegral := models.Orderfanshangintegral{
			Uid:             order.Uid,
			Integral:        integral,
			Orderfanshangid: int64(order.ID),
			State:           2,
		}
		data_source.Db.Create(&orderfanshangintegral)

		userintegral := models.Userintegral{
			Uid:        order.Uid,
			Addtime:    time.Now().Unix(),
			State:      1,
			Title:      "扭蛋机抽中隐藏积分",
			Integral:   integral,
			Syintegral: user.Integral + integral,
		}
		data_source.Db.Create(&userintegral)
		data_source.Db.Model(&models.User{}).Where("id = ?", order.Uid).Update("integral", user.Integral+integral)

	}

}

type ChoujiangRBody struct {
	Orderniudangood []models.Orderniudangood `json:"orderniudangood"`
	Usershangjuan   []models.Usershangjuan   `json:"usershangjuan"`
	Integral        int64                    `json:"integral" gorm:"integral"`
	Status          int64                    `json:"status" gorm:"status"` //1积分 2赏卷 3无隐藏奖励
}

func Choujiang(ctx *gin.Context) {
	request := GoodsBody{}
	ctx.ShouldBind(&request)
	id := request.ID

	var orderniudan models.Orderniudan
	data_source.Db.Where("id = ?", id).First(&orderniudan)

	var integral int64
	var zhuanpan models.Zhuanpan
	data_source.Db.Where("fanshangid = ?", orderniudan.Niudanid).Where("state = 2").First(&zhuanpan)

	if orderniudan.Status == 1 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "请支付",
		})
		return
	}
	if orderniudan.Choujiang == 2 {
		var orderniudangoods []models.Orderniudangood
		data_source.Db.Where("orderniudanid = ?", id).Find(&orderniudangoods)

		var fanshangjf models.Orderfanshangintegral
		var shangjuans []models.Usershangjuan
		if zhuanpan.ID > 0 {
			if zhuanpan.Classify == 1 {
				data_source.Db.Where("orderfanshangid = ?", id).Where("state = 2").First(&fanshangjf)
				if fanshangjf.ID > 0 {
					integral = fanshangjf.Integral
					orderniudangjifen := models.Orderniudangood{
						Goodname:  "积分",
						Num:       integral,
						Goodimage: "http://interstellar-tide-play.oss-cn-shanghai.aliyuncs.com/shequ/2024-10-27/1730020800积分@3x.png",
						State:     2,
					}
					orderniudangoods = append(orderniudangoods, orderniudangjifen)
				}

			} else if zhuanpan.Classify == 2 {
				data_source.Db.Where("orderfanshangid = ?", id).Where("state = 2").Find(&shangjuans)
				if len(shangjuans) > 0 {
					var sjnum int64
					for _, s := range shangjuans {
						sjnum = sjnum + s.Num
					}
					orderniudangsj := models.Orderniudangood{
						Goodname:  "赏券",
						Num:       sjnum,
						Goodimage: "http://interstellar-tide-play.oss-cn-shanghai.aliyuncs.com/shequ/2024-10-27/1730020843赏券@3x.png",
						State:     3,
					}
					orderniudangoods = append(orderniudangoods, orderniudangsj)
				}
			}
		}
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    orderniudangoods,
			"msg":     "ok",
		})
		return
	} else {
		var niudan models.Niudan
		data_source.Db.Where("id = ?", orderniudan.Niudanid).First(&niudan)

		var fanshanggoods []models.Fanshanggood
		var shangjuan models.Shangjuan
		if zhuanpan.ID > 0 {
			dengji := strings.Split(zhuanpan.Dengji, ",")
			if dengji[0] == "" {
				data_source.Db.Where("fanshangid = ?", orderniudan.Niudanid).Find(&fanshanggoods)
			} else {
				data_source.Db.Where("fanshangid = ?", orderniudan.Niudanid).Where("classify not in (?)", dengji).Find(&fanshanggoods)
			}
			if zhuanpan.Classify == 2 {
				data_source.Db.Where("id = ?", zhuanpan.Shangjuanid).First(&shangjuan)
			}
		} else {
			data_source.Db.Where("fanshangid = ?", orderniudan.Niudanid).Find(&fanshanggoods)
		}

		var niudangoods []models.Niudangood
		data_source.Db.Where("niudanid = ?", orderniudan.Niudanid).Find(&niudangoods)
		var goodidarr []int64
		var anum int64
		var bnum int64
		var cnum int64
		var dnum int64
		for _, f := range niudangoods {
			if f.Classify == 1 {
				anum = anum + f.Num
			}
			if f.Classify == 2 {
				bnum = bnum + f.Num
			}
			if f.Classify == 3 {
				cnum = cnum + f.Num
			}
			if f.Classify == 4 {
				dnum = dnum + f.Num
			}
		}
		var abili float64
		var bbili float64
		var cbili float64
		var dbili float64

		for k, v := range niudangoods {

			if v.Classify == 1 {
				abili = float64(v.Num) / float64(anum)
				niudangoods[k].Bili = niudan.Chuanshuo * 100 * abili
			} else if v.Classify == 2 {
				bbili = float64(v.Num) / float64(bnum)
				niudangoods[k].Bili = niudan.Shishi * 100 * bbili
			} else if v.Classify == 3 {
				cbili = float64(v.Num) / float64(cnum)
				niudangoods[k].Bili = niudan.Putong * 100 * cbili
			} else if v.Classify == 4 {
				dbili = float64(v.Num) / float64(dnum)
				niudangoods[k].Bili = niudan.Gaoji * 100 * dbili
			}
			goodidarr = append(goodidarr, v.Goodid)
		}
		var goods []models.Goods
		data_source.Db.Where("id in (?)", goodidarr).Where("status = 1").Find(&goods)

		now := time.Now()
		zeroToday := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).Unix()
		var user models.User
		data_source.Db.Where("id = ?", orderniudan.Uid).First(&user)
		var orderniudangoods []models.Orderniudangood
		var usershangjuans []models.Usershangjuan
		for i := 0; i < int(orderniudan.Num); i++ {
			goodid, dengji := service.GetResult(niudangoods)
			for _, good := range goods {
				if goodid == good.ID {
					orderniudangood := models.Orderniudangood{
						Uid:           orderniudan.Uid,
						Goodid:        goodid,
						Goodname:      good.Name,
						Goodimage:     good.Image,
						Goodmojing:    good.Mojing,
						Goodprice:     good.Price,
						Orderniudanid: int64(id),
						Addtime:       zeroToday,
						Num:           1,
						Dengji:        dengji,
						State:         1,
					}
					orderniudangoods = append(orderniudangoods, orderniudangood)
					service.Gooduser(user, good, 1, 2, 1, 0, id)
				}
			}

			addtime := time.Now().Unix()
			if zhuanpan.ID > 0 {
				zhongjian := service.CalculateProbability(int64(zhuanpan.Bili * 100))
				if zhongjian == true {
					if zhuanpan.Classify == 1 {
						integral = integral + zhuanpan.Integral*zhuanpan.Num
					} else if zhuanpan.Classify == 2 {
						if shangjuan.ID > 0 {
							var endtime int64
							if shangjuan.Day > 0 {
								endtime = addtime + shangjuan.Day*864000
							}
							var sjnum int64
							for iu := 0; iu < int(zhuanpan.Num); iu++ {

								usershangjuan := models.Usershangjuan{
									Uid:             orderniudan.Uid,
									Addtime:         addtime,
									Day:             shangjuan.Day,
									Name:            shangjuan.Name,
									Image:           shangjuan.Image,
									Daibi:           shangjuan.Daibi,
									Num:             shangjuan.Num,
									Userdaibi:       shangjuan.Userdaibi,
									Status:          1,
									Orderfanshangid: int64(id),
									Endtime:         endtime,
									Shangjuanid:     shangjuan.ID,
									State:           2,
								}
								usershangjuans = append(usershangjuans, usershangjuan)
								sjnum = sjnum + shangjuan.Num
							}
							orderniudangsj := models.Orderniudangood{
								Goodname:  "赏券",
								Num:       sjnum,
								Goodimage: "http://interstellar-tide-play.oss-cn-shanghai.aliyuncs.com/shequ/2024-10-27/1730020843赏券@3x.png",
								State:     3,
							}
							orderniudangoods = append(orderniudangoods, orderniudangsj)

						}
					}

				}
			}

		}

		data_source.Db.Create(&orderniudangoods)
		data_source.Db.Model(&models.Orderniudan{}).Where("id = ?", id).Update("choujiang", 2)

		if len(usershangjuans) > 0 {
			data_source.Db.Create(&usershangjuans)
		}
		if integral > 0 {
			orderfanshangintegral := models.Orderfanshangintegral{
				Uid:             orderniudan.Uid,
				Integral:        integral,
				Orderfanshangid: int64(id),
				State:           2,
			}
			data_source.Db.Create(&orderfanshangintegral)

			userintegral := models.Userintegral{
				Uid:        orderniudan.Uid,
				Addtime:    time.Now().Unix(),
				State:      1,
				Title:      "扭蛋机抽中隐藏积分",
				Integral:   integral,
				Syintegral: user.Integral + integral,
			}
			data_source.Db.Create(&userintegral)
			data_source.Db.Model(&models.User{}).Where("id = ?", orderniudan.Uid).Update("integral", user.Integral+integral)
			orderniudangjifen := models.Orderniudangood{
				Goodname:  "积分",
				Num:       integral,
				Goodimage: "http://interstellar-tide-play.oss-cn-shanghai.aliyuncs.com/shequ/2024-10-27/1730020800积分@3x.png",
				State:     2,
			}
			orderniudangoods = append(orderniudangoods, orderniudangjifen)
		}

		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    orderniudangoods,
			"msg":     "ok",
		})
		return
	}

}

func Niudansq(ctx *gin.Context) {
	request := GoodsBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	var orderniudans []models.Orderniudan
	data_source.Db.Where("niudanid = ?", id).Find(&orderniudans)
	var orderidarr []int64
	for _, v := range orderniudans {
		orderidarr = append(orderidarr, v.ID)
	}
	var orderniudangood []models.Orderniudangoodsql
	data_source.Db.Model(&models.Orderniudangood{}).Select("orderniudangood.*, user.nickname, user.logo").Joins("left join user on user.id = orderniudangood.uid").Where("orderniudangood.orderniudanid in (?)", orderidarr).Limit(10).Order("goodprice desc").Find(&orderniudangood)
	var orderniudangoodtwo []models.Orderniudangoodsql
	for _, o := range orderniudangood {
		cunzai := 1
		for _, ot := range orderniudangoodtwo {
			if o.Uid == ot.Uid {
				cunzai = 2
			}
		}
		if cunzai == 1 {
			orderniudangoodtwo = append(orderniudangoodtwo, o)
		}
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    orderniudangoodtwo,
		"msg":     "ok",
	})
	return
}

type BuyndlistRBody struct {
	Name     string `json:"name" gorm:"name"`
	Image    string `json:"image" gorm:"image"`
	Addtime  int64  `json:"addtime" gorm:"addtime"`
	Classify int64  `json:"classify" gorm:"classify"`
	Goodname string `json:"goodname" gorm:"goodname"`
}
type BuyndclassifymsgRBody struct {
	Chuanshuo []BuyndlistRBody `json:"chuanshuo" gorm:"chuanshuo"`
	Shishi    []BuyndlistRBody `json:"shishi" gorm:"shishi"`
	Putong    []BuyndlistRBody `json:"putong" gorm:"putong"`
	Gaoji     []BuyndlistRBody `json:"gaoji" gorm:"gaoji"`
}

func Niudanbuys(ctx *gin.Context) {
	request := GoodsBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	var orderniudans []models.Orderniudan
	data_source.Db.Where("niudanid = ?", id).Find(&orderniudans)
	var orderidarr []int64
	for _, v := range orderniudans {
		orderidarr = append(orderidarr, v.ID)
	}
	//fmt.Println(orderidarr)
	var orderniudangood []models.Orderniudangoodsql
	data_source.Db.Model(&models.Orderniudangood{}).Select("orderniudangood.*, user.nickname, user.logo").Joins("left join user on user.id = orderniudangood.uid").Where("orderniudangood.orderniudanid in (?)", orderidarr).Limit(10).Order("goodprice desc").Find(&orderniudangood)

	var ashangs []BuyndlistRBody
	var bshangs []BuyndlistRBody
	var cshangs []BuyndlistRBody
	var dshangs []BuyndlistRBody

	for _, or := range orderniudangood {
		if or.Dengji == 1 {
			ashang := BuyndlistRBody{
				Name:     or.Nickname,
				Image:    or.Logo,
				Addtime:  or.Addtime,
				Classify: 1,
				Goodname: or.Goodname,
			}
			ashangs = append(ashangs, ashang)
		}
		if or.Dengji == 2 {
			bshang := BuyndlistRBody{
				Name:     or.Nickname,
				Image:    or.Logo,
				Addtime:  or.Addtime,
				Classify: 2,
				Goodname: or.Goodname,
			}
			bshangs = append(bshangs, bshang)
		}
		if or.Dengji == 3 {
			cshang := BuyndlistRBody{
				Name:     or.Nickname,
				Image:    or.Logo,
				Addtime:  or.Addtime,
				Classify: 3,
				Goodname: or.Goodname,
			}
			cshangs = append(cshangs, cshang)
		}
		if or.Dengji == 4 {
			dshang := BuyndlistRBody{
				Name:     or.Nickname,
				Image:    or.Logo,
				Addtime:  or.Addtime,
				Classify: 4,
				Goodname: or.Goodname,
			}
			dshangs = append(dshangs, dshang)
		}
	}
	data := BuyndclassifymsgRBody{
		Chuanshuo: ashangs,
		Shishi:    bshangs,
		Putong:    cshangs,
		Gaoji:     dshangs,
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return
}
